package cn.apthink.solon;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

import cn.apthink.controller.BaseResult;
import cn.apthink.controller.ResponseEnum;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
//定义统一异常反馈拦截器，index务必小于SaToken拦截器-100
@Component(index = -101)
public class GeneralExceptionInterceptor implements RouterInterceptor {

	@Override
	public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
		log.debug("=>GeneralErrorInterceptor start!");
		try {
			chain.doIntercept(ctx, mainHandler);
		} catch (Exception e) {
			log.error(e.getMessage());
			if (e instanceof NotLoginException) {
				ctx.render(BaseResult.error(ResponseEnum.ErrorNoLogin, "未登录"));
			}
			if (e instanceof NotPermissionException) {
				ctx.render(BaseResult.error(ResponseEnum.ErrorNoPermission, e.getMessage()));
			}
		} catch (Throwable e) {
			log.error(e.getMessage());
			ctx.render(BaseResult.error(ResponseEnum.ErrorUnknown, e.getMessage()));
		} finally {
			log.debug("=>GeneralErrorInterceptor end!");			
		}
	}
}
